package controllers

import (
	"github.com/astaxie/beego/httplib"
	"encoding/json"
	"github.com/astaxie/beego"
	"xiaoercaidan/publicResources/models"
	"strconv"
)

type IndexController struct {
	beego.Controller
}

// @Title IndexPage
// @Description 首页接口
// @Param   shopId    patch int64  true  string       "店铺ID"
// @router /indexPage [get]
func (this *IndexController) IndexPage() {
	hostStr := "http://"+beego.AppConfig.String("basehost")+":"+beego.AppConfig.String("baseport")
	var shopId, _ = this.GetInt64("shopId", 0)
	var BaseResult = new(models.BaseResult)
	if (shopId <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "ShopId参数不正确"
		this.Data["json"] = &BaseResult
		this.ServeJSON()
		return
	}

	reqCategory := httplib.Get(hostStr+"/v1/apis/goods/queryCategory")
	reqCategory.Param("shopId", strconv.FormatInt(shopId, 10))
	reqGoods := httplib.Get(hostStr+"/v1/apis/goods/queryGoods")
	reqGoods.Param("shopId", strconv.FormatInt(shopId, 10))

	respCategory, err := reqCategory.String()
	respGoods, err := reqGoods.String()
	if (reqCategory == nil) {
		BaseResult.Code = 100
		BaseResult.Msg = "没有更多数据了"
		this.Data["json"] = &BaseResult
		this.ServeJSON()
		return
	}

	if (err == nil) {
		var mapStrCategory = make(map[string]interface{})
		var mapStrGoods = make(map[string]interface{})
		var mapResult = make(map[string]interface{})

		json.Unmarshal([]byte(respCategory), &mapStrCategory)
		json.Unmarshal([]byte(respGoods), &mapStrGoods)
		if (mapStrCategory != nil&&mapStrCategory["data"] != nil) {
			categoryArray := mapStrCategory["data"].([]interface{})
			for index, _ := range categoryArray {
				if (categoryArray != nil&&categoryArray[index] != nil) {
					mapView := categoryArray[index].(map[string]interface{})
					goodsSlice := make([]interface{}, 0)
					for _, goodsValue := range mapStrGoods["data"].([]interface{}) {
						good := goodsValue.(map[string]interface{})
						if (good["CategoryId"] == mapView["Id"]) {
							goodsSlice = append(goodsSlice, goodsValue)
						}
					}
					mapView["goods"] = goodsSlice
				}
			}
			mapResult["category"] = mapStrCategory["data"]
		} else {
			BaseResult.Code = 100
			BaseResult.Msg = "没有更多数据了"
			this.Data["json"] = &BaseResult
			this.ServeJSON()
			return
		}

		if (mapResult != nil) {
			BaseResult.Data = mapResult
		} else {
			BaseResult.Code = 101
			BaseResult.Msg = "登录失败，用户名或则密码不匹配"
			BaseResult.Msg = "您查询的桌台不存在"
		}

		this.Data["json"] = BaseResult

	}

	this.ServeJSON()

}



